﻿using com.ruovea.ddns.util;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.ruovea.tencent.dnspod
{
    public class TencentDomainRecord : IDomainRecord
    {
        IConfiguration _configuration;

        string _recordId = string.Empty;

        DnsPod dnsPod = null;
        public TencentDomainRecord(IConfiguration configuration)
        {
            this._configuration = configuration;
         
            string token = _configuration.GetSection("dnspod:token")?.Value;

            _recordId = _configuration.GetSection("dnspod:recordId")?.Value;

            dnsPod = new DnsPod( token);
        }
        public IEnumerable<DescribeRecord> GetRecords(string domainName)
        {
            var paramObject = new { domain = domainName, record_id = _recordId };
            dynamic data = dnsPod.PostApiRequest("Record.Info", paramObject);

            if (data != null && data.status.code == 1)
            {
                return new List<DescribeRecord>{new DescribeRecord()
                {
                    RecordId = data.record.id,
                    Value = data.record.value,
                    RR = data.record.ttl,
                    Type = data.record.record_type
                }};
            }
            return null;
        }

        public void Refresh()
        {
            string domain = _configuration.GetSection("dnspod:domain")?.Value?.Trim();

            var current_ip = IpHelper.CurrentIp();
            var records = this.GetRecords(domain);

            records = records.Where(x => x.Type == "A");

            if (!records.Any(x => x.Value != current_ip))
            {
                Console.WriteLine($"{DateTime.Now} ip没有改变 {current_ip}");
                return;
            }

            Console.WriteLine($"{DateTime.Now} 更新A解析记录 {current_ip}");

            // 更新记录
            foreach (var item in records)
            {
                item.Value = current_ip;
                this.UpdateRecord(item);
            }
        }

        public void UpdateRecord(DescribeRecord record)
        {
            try
            {
                var current_ip = IpHelper.CurrentIp();
                var paramObject = new { domain = record.DomainName, record_id = _recordId, record_line = "默认", value = current_ip };
                var response = dnsPod.PostApiRequest("Record.Ddns", paramObject);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}
